package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.SetmealDao;
import com.itheima.dto.SetmealDto;
import com.itheima.po.Setmeal;
import com.itheima.po.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Transactional
        public void saveWithDish(SetmealDto setmealDto){
//        1、添加套餐
            this.save(setmealDto);
//            2、添加套餐菜品关系
            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
        }

    @Override
    public void deleteWithDish(Long[] ids) {

    }


    @Transactional
    @Override
    public void deleteWithDish(List<Long> ids) {
        /*步骤ids单个删除与批量删除*/
//        售卖中的套餐不能删除
//        所有要删除的套餐为停售状态，则删除套餐数据以及套餐菜品数据
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);
        Long countInSaling = this.count(lambdaQueryWrapper);
//        如果>0说明有套餐为启用状态，在售卖中
        if (countInSaling>0){
            throw new RuntimeException("套餐正在售卖中，不能删除");
        }
//        根据ids批量删除套餐数据
        this.removeByIds(ids);
//        根据套餐IDs批量套餐数据菜品
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);

    }
}


